package modules

import (
	"service/components"
	"time"

	"gorm.io/gorm"
)

// Attribute 商品的展示参数
type Attribute struct {
	Id        int64          `json:"id" gorm:"primaryKey"`
	Name      string         `json:"name" form:"name" gorm:"size:300;comment:属性名字;"`
	Type      string         `json:"type" form:"type" gorm:"comment:属于哪一个类型的;size:50"`
	IsParent  int64          `json:"is_parent" form:"is_parent" gorm:"comment:父级ID"`
	Attribute string         `json:"attribute" form:"attribute" gorm:"comment:属性"`
	Display   string         `json:"display" form:"display" gorm:"size:5;comment:显示和隐藏的切换;default:1"`
	Uid       int64          `json:"uid" form:"uid" gorm:"comment:添加标签的用户ID"`
	Children  []*Attribute   `json:"children" form:"children" gorm:"foreignKey:Uid"`
	CreatedAt time.Time      `json:"created_at" form:"created_at" gorm:"comment:创建时间"`
	DeletedAt gorm.DeletedAt `json:"deleted_at" form:"deleted_at" gorm:"comment:删除时间"`
}

func (c Attribute) TableName() string {
	return "attribute"
}

// GetAllAttributeService 根据类型获取所有的标签
func GetAllAttributeService(_type string, display string) ([]Attribute, error) {
	db := components.DB.Model(&Attribute{})
	var cc []Attribute
	if display == "1" {
		err := db.Where("type = ?", _type).Find(&cc).Error
		if err != nil {
			return nil, err
		}
		return cc, err
	} else {
		err := db.Where("type = ? AND display = ?", _type, "1").Find(&cc).Error
		if err != nil {
			return nil, err
		}
		return cc, err
	}
}

// AddAttributeService 增加售卖商品总类的属性
func AddAttributeService(attribute *Attribute) error {
	err := components.DB.Model(Attribute{}).Create(attribute).Error
	if err != nil {
		return err
	}
	return nil
}

// GetAttributeByNameAndTypeService 根据名字获取商品总类属性
func GetAttributeByNameAndTypeService(cc Attribute) int64 {
	var c Attribute
	return components.DB.Model(Attribute{}).
		Where("name = ? AND type = ? AND is_parent = ?", cc.Name, cc.Type, cc.IsParent).Take(&c).RowsAffected
}

func DeleteAttributeService(c *Attribute) error {
	return components.DB.Model(Attribute{}).
		Where("name = ? AND type = ?", c.Name, c.Type).Delete(c).Error
}
